var score = 0;
var timer;
//存储图片路径
var srcAll = ["img/1.jpg","img/2.jpg","img/3.jpg",
				"img/4.jpg","img/5.jpg","img/6.jpg",
				"img/7.jpg","img/8.jpg","img/1.jpg",
				"img/2.jpg","img/3.jpg","img/4.jpg",
				"img/5.jpg","img/6.jpg","img/7.jpg",
				"img/8.jpg"];

//页面加载后执行
$(document).ready(function(){
	newgame();
	$("#newgamebutton").on("click",function(){
		newgame();
		countDown();
	})
})


//新游戏
function newgame(){
	//初始化
	//生成不重复的随机数
	addScore(0);
	window.clearInterval(timer);
	score = 0;
	console.log(score);
	var arr = [];
	var result = [];
	for(var i=0;i<100;i++){
		arr[i] = Math.floor(Math.random()*16);
	}
	arr.forEach(function(item,index){
		if(result.indexOf(item) == -1 && result.length<=16){
			result.push(item);
		}
	})
	//添加图片src
	var img = $("<img />");
	if($(".grid-cell").children("img").length == 0){
		img.appendTo($(".grid-cell"));
	}
	for(let i=0;i<result.length;i++){
		$(".grid-cell img").eq(i).prop("src",srcAll[result[i]]);
	}
	$(".active").removeClass("active");
	$(".judge").removeClass("judge");
	$(".namei").css({
		"opacity":"0"
	});
	$("#score").text("0");
	$(".grid-cell").css("transform","");
}
//点击显示
$(".grid-cell").on("click",function(){
	if($(".judge").length<2 && $(".active").length<16 && !$(this).hasClass("active")){
		$(this).addClass("judge");
		$(this).css("transform","rotateY(180deg)");
	}
	if($(".judge").length==2){
		judge(score);
	}
	if($(".active").length == 16){
		$(".namei").css({
			"opacity":"1"
		});
		window.clearInterval(timer);
	}
//	if(!$(this).hasClass("active")){
//		$(this).css("transform","");
//	}
})

//判断是否相等
function judge(score){
	if($(".judge").children("img").eq(0).prop("src") == $(".judge").children("img").eq(1).prop("src")){
		$(".judge").addClass("active").removeClass("judge");
		//addScore();
	}else{
		setTimeout(function(){
			$(".judge").css("transform","");
			$(".judge").removeClass("judge");
		},500)
	}
}
function addScore(score){
//	score = $(".active").length;
	//console.log(score);
	$("#score").text(score);
	$(".score").text(score);
}

//60秒倒计时
function countDown(){
	timer = setInterval(function(){
		score += 1;
		addScore(score);
	},1000)
}

//开始计时
$("#grid-container").one("click",function(){
	countDown();
})
